package com.chukun.multi.masterslave.reusable;

import java.util.*;
import java.util.concurrent.Future;

/**
 * 轮询策略分发器
 * @param <T>
 * @param <V>
 */
public class RoundRobinSubTaskDispatchStrategy<T,V> implements SubTaskDispatchStrategy<T,V> {
    @Override
    public Iterator<Future<V>> dispatch(Set<? extends SlaveSpec<T, V>> slaves,
                                        TaskDivideStrategy<T> taskDivideStrategy) throws InterruptedException {
        final List<Future<V>> subResults = new LinkedList<>();
        T subTask;
        Object[] slaveArray = slaves.toArray();
        int i = -1;
        final int slaveCount = slaveArray.length;
        Future<V> subTaskResultPromise;
        while (taskDivideStrategy.nextChunk().isPresent()) {
              subTask = taskDivideStrategy.nextChunk().get();
              i = (i + 1) % slaveCount;
              subTaskResultPromise = ((WorkerThreadSlave<T,V>)slaveArray[i]).submit(subTask);
              subResults.add(subTaskResultPromise);
        }
        return subResults.iterator();
    }
}
